package com.zk.code.net;

import com.example.imgrecognition.Util.ArrayUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class UdpClientFileHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private int byteRead;
    private volatile int start = 0;
    private volatile int lastLength = 0;
    public RandomAccessFile randomAccessFile;
    private ByteBuf filebye;

    public UdpClientFileHandler(ByteBuf filebye) {
        this.filebye = filebye;
    }

    //每帧数据要小于1417
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {
        //start = fileUploadFiles.getStarPos();
        //65535
        System.err.println("在这里执行了");
        ByteBuf byteBuf = datagramPacket.content();
        int len = byteBuf.readInt();
        int receivLen = byteBuf.readableBytes();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        if(receivLen < len){
            return;
        }else{
            if(receivLen<=60000){
                System.err.println(Arrays.toString(bytes));
                ctx.writeAndFlush(bytes);
            }else{
                int count = (int)receivLen/60000;
                List<byte[]> list = ArrayUtil.spliteArray(bytes,count);
                for(int i=0;i<list.size();i++){
                    System.err.println(Arrays.toString(list.get(i)));
                    ctx.writeAndFlush(list.get(i));
                }
            }


        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("在这里执行了111");
        ByteBuf byteBuf = filebye;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        System.err.println("bytes-->"+Arrays.toString(bytes));
        ctx.writeAndFlush(bytes);
        byteBuf.release();

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        Channel incomming = ctx.channel();
        if(!incomming.isActive()){
            System.err.println("connection close");
        }
        ctx.close();
    }
}
